﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsFAQTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// FAQ Business Object
    /// </summary>

    public class FAQ : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected FAQ() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the FAQ.
        /// </summary>
        public int FAQID
        {
            get { return _faqID; }
            set
            {
                if (_faqID != value)
                {
                    if (OnPropertyChanging("FAQID", _faqID, value))
                    {
                        int oldValue = _faqID;
                        _faqID = value;

                        OnPropertyChanged("FAQID", oldValue, value);
                    }
                }
            }
        }  private int _faqID = -1;






        /// <summary>
        /// FAQFor,.
        /// </summary>
        public string FAQFor
        {
            get { return _faqfor; }
            set
            {
                if (_faqfor != value)
                {
                    if (OnPropertyChanging("FAQFor,", _faqfor, value))
                    {
                        string oldValue = _faqfor;
                        _faqfor = value;
                        OnPropertyChanged("FAQFor,", oldValue, value);
                    }
                }
            }
        }  private string _faqfor = null;








        /// <summary>
        /// QuestionCategory.
        /// </summary>
        public string QuestionCategory
        {
            get { return _questioncategory; }
            set
            {
                if (_questioncategory != value)
                {
                    if (OnPropertyChanging("QuestionCategory,", _questioncategory, value))
                    {
                        string oldValue = _questioncategory;
                        _questioncategory = value;
                        OnPropertyChanged("QuestionCategory,", oldValue, value);
                    }
                }
            }
        }  private string _questioncategory = null;








        /// <summary>
        /// Question.
        /// </summary>
        public string Question
        {
            get { return _question; }
            set
            {
                if (_question != value)
                {
                    if (OnPropertyChanging("Question", _question, value))
                    {
                        string oldValue = _question;
                        _question = value;
                        OnPropertyChanged("Question", oldValue, value);
                    }
                }
            }
        }  private string _question = null;


        /// <summary>
        /// Answer.
        /// </summary>
        public string Answer
        {
            get { return _answer; }
            set
            {
                if (_answer != value)
                {
                    if (OnPropertyChanging("Answer", _answer, value))
                    {
                        string oldValue = _answer;
                        _answer = value;
                        OnPropertyChanged("Answer", oldValue, value);
                    }
                }
            }
        }  private string _answer = null;


        /// <summary>
        /// Date/time at which the JobCategory was created.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the JobCategory was updated.
        /// </summary>
        public DateTime? UpdatedDate
        {
            get { return _updatedDate; }
            set
            {
                if (_updatedDate != value)
                {
                    if (OnPropertyChanging("UpdatedDate", _updatedDate, value))
                    {
                        DateTime? oldValue = _updatedDate;
                        _updatedDate = value;
                        OnPropertyChanged("UpdatedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updatedDate = null;

        
        /// <summary>
        /// True iff the Admin has made this JobCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;





        /// <summary>
        /// True iff the Admin has made this FAQ Active (i.e. to be used in the application).
        /// </summary>
        public bool IsMostPopular
        {
            get { return _ismostpopular; }
            set
            {
                if (_ismostpopular != value)
                {
                    if (OnPropertyChanging("IsMostPopular", _ismostpopular, value))
                    {
                        bool oldValue = _ismostpopular;
                        _ismostpopular = value;
                        OnPropertyChanged("IsMostPopular", oldValue, value);
                    }
                }
            }
        }  private bool _ismostpopular = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty JobCategory object.
        /// </summary>
        public static FAQ CreateNew()
        {
            FAQ obj = new FAQ();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            obj.UpdatedDate = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static FAQ CreateNew(FAQCollection collection)
        {
            FAQ obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (FAQ faq in collection)
            {
                if (faq.FAQID < minVal)
                    minVal = faq.FAQID;
            }
            obj.FAQID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllFAQ

        /// <summary>
        /// Returns a collection of all FAQ.
        /// </summary>
        public static FAQCollection GetAllFAQ()
        {
            FAQTableAdapter adapter = new FAQTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsFAQ.FAQDataTable tbl = adapter.GetData(null);

            FAQCollection list = new FAQCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsFAQ.FAQRow row in tbl.Rows)
                {
                    FAQ faq = new FAQ();
                    RelationalToObject(faq, row);
                    list.Add(faq);
                }
            }

            return (list);
        }

        #endregion

        #region GetFAQByID

        /// <summary>
        /// Returns an FAQ object for the specified 'FAQID' or null if no FAQ with the specified parameter(s) exists.
        /// </summary>
        public static FAQ GetFAQByID(int faqid)
        {
            FAQTableAdapter adapter = new FAQTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsFAQ.FAQDataTable tbl = adapter.GetData(faqid);

            if (tbl.Rows.Count == 1)
            {
                FAQ faq = new FAQ();
                RelationalToObject(faq, tbl.Rows[0]);
                return (faq);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

            return (null);
        }

        #endregion

        //#region GetFAQByQuestion

        ///// <summary>
        ///// Returns an FAQ object for the specified 'FAQQUESTION' or null if no FAQ with the specified parameter(s) exists.
        ///// </summary>
        //public static FAQ GetFAQByQuestion(string faqquestion)
        //{
        //    FAQTableAdapter adapter = new FAQTableAdapter();
        //    adapter.Connection = AppSettings.GetDbConn();
        //    dsFAQ.FAQDataTable tbl = adapter.GetDataBySelectByQuestion(faqquestion);

        //    if (tbl.Rows.Count == 1)
        //    {
        //        FAQ faq = new FAQ();
        //        RelationalToObject(faq, tbl.Rows[0]);
        //        return (faq);
        //    }
        //    else if (tbl.Rows.Count > 1)
        //        throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

        //    return (null);
        //}

        //#endregion

        #region GetFAQByForAndIsMostPopular

        /// <summary>
        /// Returns an FAQ object for the specified 'ForAndIsMostPopular' or null if no FAQ with the specified parameter(s) exists.
        /// </summary>
        public static FAQ GetFAQByForAndIsMostPopular(string byfor, Boolean ismostpopular)
        {
            FAQTableAdapter adapter = new FAQTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsFAQ.FAQDataTable tbl = adapter.GetDataByForAndIsMostPopular(byfor, ismostpopular);

            if (tbl.Rows.Count == 1)
            {
                FAQ faq = new FAQ();
                RelationalToObject(faq, tbl.Rows[0]);
                return (faq);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

            return (null);
        }

        #endregion


        #region Update

        /// <summary>
        /// Updates the specified FAQ.
        /// </summary>
        public static void Update(FAQ obj)
        {
            bool updateFAQ = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateFAQ = (obj.ObjState != ObjectState.Unchanged);

                if (!updateFAQ)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsFAQ.FAQDataTable tbl = null;
            if (updateFAQ)
            {
                FAQTableAdapter adapter = new FAQTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsFAQ.FAQDataTable();
                dsFAQ.FAQRow row = tbl.NewFAQRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (FAQID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("FAQID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((Question == null) || (Question.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("Question", "Question is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {
                    
                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("FAQ: FAQID={0}, Question={1}, {2}", FAQID, Question, Answer));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more FAQ objects.
    /// </summary>

    public class FAQCollection : List<FAQ>
    {
        #region Types

        public class UserComparer : IComparer<FAQ>
        {
            public int Compare(FAQ q1, FAQ q2)
            {
                return (String.Compare(q1.Question, q2.Question));
            }
        }

        #endregion

        #region Public Methods

        #region FindByFAQID

        public FAQ FindByFAQID(int faqID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].FAQID == faqID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindFAQByQuestion

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public FAQ FindFAQByQuestion(string faqquestion)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].Question == faqquestion)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
